﻿using System;
using System.Runtime.InteropServices;
using JamesZhao.Engine.Graphics.Surfaces;
using SlimDX;
using SlimDX.Direct3D11;
using SlimDX.DXGI;
using SlimMath;
using MapFlags = SlimDX.Direct3D11.MapFlags;
using Vector2 = SlimMath.Vector2;

namespace JamesZhao.Engine.Graphics.RenderStages
{
    public class ReadGpuValueStage : RenderStage
    {
        public override string Name
        {
            get { return "Read Scalar"; }
        }

        public ColorSurface RawColorSurface;
        public ColorSurface CpuColorSurface;

        protected override void OnRender(GraphicsDevice device, SwapChain swapChain, VisualsList visualsList, Camera camera)
        {

            device.ImmediateContext.CopyResource(
                RawColorSurface.Texture,
                CpuColorSurface.Texture);
            var dataStream = device.ImmediateContext.MapSubresource(CpuColorSurface.Texture, 0,
                                                                    4, MapMode.Read, MapFlags.None);
            Half x, y;
            Half[] val = dataStream.Data.ReadRange<Half>(1);
            x = val[0];
            val = dataStream.Data.ReadRange<Half>(1);
            y = val[0];
            device.ImmediateContext.UnmapSubresource(CpuColorSurface.Texture, 0);

            Result = new Vector2(x, y);
            //Console.WriteLine(Result);
        }

        public Vector2 Result { get; set; }
    }
}
